﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Media;
using PowerManager.Properties;

namespace PowerManager
{
	public partial class WarningForm : Form
	{
		public WarningForm(PowerAction action, int seconds, string message)
		{
			ShowElements(action, seconds);
			reasonLabel.Show();
			userMessageBox.Show();
			userMessageBox.Text = message;
		}

		public WarningForm(PowerAction action, int seconds)
		{
			ShowElements(action, seconds);
			reasonLabel.Hide();
			userMessageBox.Hide();
		}

		private void ShowElements(PowerAction action, int seconds)
		{
			InitializeComponent();
			
			SoundPlayer player = new SoundPlayer(Resources.sound);
			player.Play();

			fTimer1.Timer =  EventTime.GetTimeBySeconds(seconds);
			this.action = action;
			switch (action)
			{
				case PowerAction.Halt:
					actionLabel.Text = "Your computer will be\r\nshutdown by administrator";
					break;
				case PowerAction.Reboot:
					actionLabel.Text = "Your computer will be\r\nrebooted by administrator";
					break;
				case PowerAction.Hibernate:
					actionLabel.Text = "Your computer will be\r\nhibernated by administrator";
					break;
				case PowerAction.Suspend:
					actionLabel.Text = "Your computer will be\r\nsuspended by administrator";
					break;
				case PowerAction.Logoff:
					actionLabel.Text = "Your computer will be\r\nlogged off by administrator";
					break;
			}
			fTimer1.Start();
			fTimer1.TimerElapsed += new FTimerElapsedEventHandler(FTimerElapsedProc);
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Right - this.Width, Screen.PrimaryScreen.WorkingArea.Bottom - this.Height);
			base.OnPaint(e);
		}

		private void FTimerElapsedProc(object sender, EventArgs e)
		{
			die = true;
			this.Close();
		}

		public bool die = false;
		
		private PowerAction action;

		// Magic to move form anywhere
		protected override void WndProc(ref Message m)
		{
			const int WM_NCHITTEST = 0x84;
			const int HTCLIENT = 0x01;
			const int HTCAPTION = 0x02;

			if (m.Msg == WM_NCHITTEST)
			{
				this.DefWndProc(ref m);
				if (m.Result == new IntPtr(HTCLIENT))
					m.Result = new IntPtr(HTCAPTION);
				else
					base.WndProc(ref m);
			}
			else
				base.WndProc(ref m);
		}

		private void WarningForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (!die)
				e.Cancel = true;
		}
	}
}
